package com.util;

import de.mkammerer.argon2.Argon2;
import de.mkammerer.argon2.Argon2Factory;

/**
 * 校验位工具
 * Created by yuansf on 2018/6/28.
 */
public class Argon2Util {
    /**
     * 采用默认的变体= argon2i（默认）salt=16字节（默认） 哈希长度=32字节（默认）
     */
    private static final Argon2 ARGON2 = Argon2Factory.create();
    /**
     * 迭代次数
     */
    private static final int ITERATIONS = 2;
    /**
     * memory内存设置为64M
     */
    private static final int MEMORY = 65536;
    /**
     * Number of threads and compute lanes
     * 线程通道数
     */
    private static final int PARALLELISM = 1;


    public static String encode(CharSequence rawPassword) {
        final String hash = ARGON2.hash(ITERATIONS, MEMORY, PARALLELISM, rawPassword.toString());
        String prefix = "$ag2" + "$19" + "$" + MEMORY + "," + ITERATIONS + "," + PARALLELISM + "$";
        StringBuffer result = new StringBuffer();
        String[] split = hash.split("\\$");
        String suffix = split[split.length - 2] + "." + split[split.length - 1];
        result.append(prefix);
        result.append(suffix);
        return result.toString();
    }


    public static boolean matches(CharSequence rawPassword, String encodedPassword) {
        StringBuffer password = new StringBuffer();
        String[] split = encodedPassword.split("\\$");
        String prefix = "$argon2i" + "$v=19" + "$m=" + MEMORY + ",t=" + ITERATIONS + ",p=" + PARALLELISM + "$";
        String[] suffixList = split[split.length - 1].split("\\.");
        String suffix = suffixList[0] + "$" + suffixList[suffixList.length - 1];
        password.append(prefix);
        password.append(suffix);
        return ARGON2.verify(password.toString(), rawPassword.toString());

    }

    public static void main(String[] args) {

        String hashedPassword = Argon2Util.encode("90df1f98d0c281188662656262e8c139");
        System.out.println(hashedPassword);
        System.out.println(Argon2Util.matches("90df1f98d0c281188662656262e8c139", "$ag2$19$65536,2,1$GqI42rXBTfJhxwh3GSxvfQ.AuQki/HIWUpGQS0Bt7k3FtVZVZw5zj9aKzNa5rtUK5s "));
    }

}
